Dynamic memory allocation, also known as heap-based memory allocation, is the allocation of memory storage for use in a computer program during the runtime of that program. It can also be seen as a way of distributing ownership of limited memory resources among many pieces of data and code. Dynamically allocated memory exists until it is freed. This is in contrast to static memory allocation, which has a fixed duration.
Usually, memory is allocated from a large pool of unused memory area called the heap (also called the free store). Since the precise location of the allocation is not known in advance, the memory is accessed indirectly, usually via a reference or pointer. For example, malloc is a library function for performing dynamic memory allocation in the C and C++ programming languages. It is typically part of a standard library for both languages.
A program or process accesses an allocated block or chunk of memory via a pointer returned by a memory allocation function such as malloc. A block or chunk of memory allocated in this manner is persistent in that it will remain allocated until the program terminates or the memory is explicitly deallocated, or “freed.” This is typically achieved by the use of a free memory function.
When a call to malloc succeeds, the return value of the call should eventually be passed to the free memory function. This releases the allocated memory block or chunk in the heap, allowing it to be reused to satisfy other memory allocation requests. If a memory chunk is not freed, a memory leak will occur in that the allocated memory will not be released until the process exits, and in some environments, not even then. Such memory leaks are especially problematic in long-running systems, such as embedded systems.